import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import storage from 'store'
import store from '@/store'
import configs from "@/config/defaultSettings"
import { sortJson } from '@/utils/sortJson'
import { signature, verify } from '@/utils/sign'
import qs from 'qs'
import md5 from 'md5'
import { message } from 'ant-design-vue'
import router from '../router'
import { i18nRender } from "@/locales";
let url = `${process.env.VUE_APP_API_BASE_URL}/api/file/uploadImage`
export function upload(formData) {

  return new Promise((resolve, reject) => {

    const token = storage.get(ACCESS_TOKEN)
    const keyServeId = storage.get('keyServeId')
    let xhr = new XMLHttpRequest();
    xhr.open('post', url);
    xhr.setRequestHeader("source", configs.source);
    xhr.setRequestHeader("tokenId", token);
    xhr.setRequestHeader("secretKeyId", keyServeId);

    xhr.onreadystatechange = function () { 
      if (xhr.readyState == 4) {
        if (xhr.status === 200) {
          if (isJSON(xhr.responseText)) {
            resolve(JSON.parse(xhr.responseText))
            let response = JSON.parse(xhr.responseText) 
            let publicKey = storage.get('keyServe')
            let data = JSON.parse(JSON.stringify(response))
            // 删除
            if (response.signature) {
              delete data.signature;
            }
            // 对返回json数据排序
            let sorted = sortJson(data)
            // 排序结果md5
            let mds = md5(JSON.stringify(sorted))
            // 对返回结果验证签名
            let result = verify(response.signature, mds.toUpperCase(), publicKey)
 

            // 验证失败,提示错误,重新获取签名
            if (result == false) { 
              message.error(i18nRender('notice.msg.tokenNetwork'))
              storage.remove('keyServeId')
              storage.remove('keyServe')
              storage.remove('keyB')
              storage.remove('keyR')
              store.commit("SET_SKEY",);
              return
            }
            if (response.code === 100003) {
              storage.remove(ACCESS_TOKEN)
              storage.remove(USER_INFO)
              store.commit("SET_LOGIN",);
              router.push('/')
              return
            }
            else if (response.code === 100038) {
              message.error(i18nRender('notice.msg.tokenNetwork'))
              /* 
              验签失败，重新本地签名
              */
              storage.remove('keyServeId')
              storage.remove('keyServe')
              storage.remove('keyB')
              storage.remove('keyR')
              store.commit("SET_SKEY",);
              return
            }
            else if (response.code != 0) {
              message.error(response.msg)
            }
          } else {
            resolve(xhr.responseText)
          }
        } else {
          reject(xhr.responseText)
        }
      }

    }
    xhr.send(formData);
  });

}

function isJSON(str) {
  if (typeof str == 'string') {
    try {
      var obj = JSON.parse(str);
      if (typeof obj == 'object' && obj) {
        return true;
      } else {
        return false;
      }
    } catch (e) {
      return false;
    }
  }
}